import {
  fetchListAsync,
  createItemAsync,
  updateItemAsync,
  deleteItemAsync,
  fetchFilterOptsAsync,
  IDepartmentListItem,
} from '@/services/manageDepartment';
import generateCommonModel, {
  CommonModelState,
  CommonModelEffects,
  CommonModelReducers,
} from '@/utils/redux';
import _ from 'lodash';

export type ManageDepartmentModelState = CommonModelState;

export interface ManageDepartmentModelType {
  namespace: string;
  state: ManageDepartmentModelState;
  effects: CommonModelEffects;
  reducers: CommonModelReducers<ManageDepartmentModelState>;
}

const CommonModal: ManageDepartmentModelType = generateCommonModel('manageDepartment', {
  fetchListApi: fetchListAsync,
  createItemApi: createItemAsync,
  updateItemApi: updateItemAsync,
  deleteItemApi: deleteItemAsync,
  fetchFilterOptsApi: fetchFilterOptsAsync,
});

const ExtendModel: Partial<ManageDepartmentModelType> = {
  effects: {
    *queryTableList({ payload }, { call, put }) {
      const res = yield call(fetchListAsync, payload);

      if ('0' === res.code) {
        let { records = [], total = 0 } = res.data;

        const newData = records.map((item: IDepartmentListItem) => {
          const data = { ...item, ...item.extraInfoMap };

          delete data.children;

          return data;
        });

        yield put({
          type: 'saveTableList',
          payload: newData,
        });
        yield put({
          type: 'saveTotal',
          payload: total,
        });
      }
    },
  },
};

const ManageDepartmentModel = _.merge(CommonModal, ExtendModel);

export default ManageDepartmentModel;
